package main

import (
	"fmt"
	"net"
	"net/rpc"

	"gitee.com/go-course/go8/micro/rpc/rpc_interface/service"
)

// 封装一个HelloServiceClient
var _ service.HelloService = (*HelloServiceClient)(nil)

func NewHelloServiceClient(network, address string) *HelloServiceClient {
	// 通过网络来和rpc server建立通信
	conn, err := net.Dial(network, address)
	if err != nil {
		panic(err)
	}

	// 把network交给 rpc框架处理
	client := rpc.NewClient(conn)
	return &HelloServiceClient{
		client: client,
	}
}

type HelloServiceClient struct {
	client *rpc.Client
}

// RPC Client
func (c *HelloServiceClient) Greet(request string, response *string) error {
	return c.client.Call("HelloService.Greet", request, response)
}

// 作为RPC client的使用方
func main() {
	client := NewHelloServiceClient("tcp", "localhost:1234")
	var resp string
	err := client.Greet("alice", &resp)
	if err != nil {
		panic(err)
	}
	fmt.Println(resp)
}
